<?php

namespace Glpmr\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
use Glpmr\UserBundle\Entity\User;
use Glpmr\UserBundle\Form\UserType;
use Glpmr\QuizzBundle\Entity\Promotion;

class DefaultController extends Controller {

    public function indexAction() {
        return $this->render('GlpmrUserBundle:Default:index.html.twig');
    }

    public function loginAction(Request $request) {
        // Si le visiteur est déjà identifié, on le redirige vers l'accueil
        if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
            return $this->redirect($this->generateUrl('glpmr_quizz_homepage'));
        }
        $session = $request->getSession();
        // On vérifie s'il y a des erreurs d'une précédente soumission du formulaire
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }
        return $this->render('GlpmrUserBundle:Default:login.html.twig', array(
                    // Valeur du précédent nom d'utilisateur entré par l'internaute
                    'last_username' => $session->get(SecurityContext::LAST_USERNAME),
                    'error' => $error,
        ));
    }

    public function manageAction() {
        $users = $this->getDoctrine()->getRepository('GlpmrUserBundle:User')->findAll();
        $promotions = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Promotion')->findAll();

        if (!$users) {
            throw $this->createNotFoundException(
                    'Aucun utilisateur en base de donnees'
            );
        } else {

            return $this->render('GlpmrUserBundle:Default:listUser.html.twig', array("users" => $users, "promotions" => $promotions));
        }
    }

    public function modifierUserAction($id) {
        $user = $this->getDoctrine()->getRepository('GlpmrUserBundle:User')->findOneById($id);
        $promotions = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Promotion')->findAll();

        if (!$user) {
            throw $this->createNotFoundException('L\'utilisateur n\'existe pas');
        } else {
            $request = $this->get('request');
            if ($request->getMethod() == 'POST') {
                $username = $request->request->get('username');
                $mail = $request->request->get('mail');
                $libelle = $request->request->get('promotion');
                $promotion = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Promotion')->findOneByLibelle($libelle);
                $role = $request->request->get('role');
                $userManager = $this->container->get('fos_user.user_manager');
                $user->setUsername($username);
                $user->setEmail($mail);
                $user->setPromotion($promotion);
                $user->setRoles(array($role));
                $userManager->updateUser($user, true);


                $url = $this->generateUrl("glpmr_user_manage");
                return $this->redirect($url);
            } else {
                return $this->render('GlpmrUserBundle:Default:modifierUser.html.twig', array("user" => $user, "promotions" => $promotions));
            }
        }
    }

    public function supprimerUserAction($id) {
        $user = $this->getDoctrine()->getRepository('GlpmrUserBundle:User')->findOneById($id);
        $em = $this->getDoctrine()->getManager();

        $em->remove($user);

        $em->flush();

        $url = $this->generateUrl("glpmr_user_manage");
        return $this->redirect($url);
    }

    public function importerUserAction() {
        $request = $this->get('request');
        if ($request->getMethod() == 'POST') {
            if (isset($_FILES['file'])) {
                if ($_FILES["file"]["error"] > 0) {
                    throw $this->createNotFoundException('Erreur lors de l\'upload : ' . $_FILES["file"]["error"]);
                } else {
                    $mimes = array('application/vnd.ms-excel', 'text/plain', 'text/csv', 'text/tsv');
                    if (in_array($_FILES['file']['type'], $mimes)) {
                        /*
                         * 
                         *  PARSER LE FICHIER ICI
                         *  1. on parcours le fichier csv
                         *  2. On creer un User pour chaque ligne
                         *  3. On enregistre le User courant en base
                         *  FORMAT REQUIS : username;email;password;promotion
                         */

                        $em = $this->getDoctrine()->getManager();
                        $em->getRepository('GlpmrUserBundle:User');

                        if (($handle = fopen($_FILES["file"]["tmp_name"], "r")) !== FALSE) {
                            while ($lignes = fgetcsv($handle, "", ";")) {
                                $user = new User();
                                $user->setUsername($lignes[0]);
                                $user->setEmail($lignes[1]);

                                $promotion = $this->getDoctrine()->getRepository('GlpmrQuizzBundle:Promotion')->findOneByLibelle($lignes[3]);
                                $user->setPromotion($promotion);
                                $user->setEnabled(1); // on active de base l'utilisateur importé
                                $user->setRoles(array("ROLE_ELEVE"));

                                /*
                                 *  Crypter le mot de passe, sinon ça result en "droit invalid" à la connexion 
                                 */
                                $encoder = $this->get('security.encoder_factory')->getEncoder($user);
                                $encod_pass = $encoder->encodePassword($lignes[2], $user->getSalt());
                                $user->setPassword($encod_pass);

                                $em->persist($user);
                                $em->flush();
                                $em->clear();
                            }
                        }
                        fclose($handle);

                        $url = $this->generateUrl("glpmr_user_manage");
                        return $this->redirect($url);
                    } else {
                        throw $this->createNotFoundException('Le fichier doit etre au format CSV');
                    }
                }
            } else {
                throw $this->createNotFoundException('Pas de fichier selectionn&eacute;');
            }
        } else {
            return $this->render('GlpmrUserBundle:Default:import.html.twig');
        }
    }

    public function buildPaginationLetter(array $array) {
        $letterArray = array(
            "A" => 0,
            "B" => 0,
            "C" => 0,
            "D" => 0,
            "E" => 0,
            "F" => 0,
            "G" => 0,
            "H" => 0,
            "I" => 0,
            "J" => 0,
            "K" => 0,
            "L" => 0,
            "M" => 0,
            "N" => 0,
            "O" => 0,
            "P" => 0,
            "Q" => 0,
            "R" => 0,
            "S" => 0,
            "T" => 0,
            "U" => 0,
            "V" => 0,
            "W" => 0,
            "X" => 0,
            "Y" => 0,
            "Z" => 0
        );

        foreach ($array as $user) {
            $username = $user->getUsername();
            $tmpLetter = $username{0};
            $firstLetter = strtoupper($tmpLetter);
            if (in_array($firstLetter, $letterArray)) {
                $letterArray[$firstLetter] = 1;
            }
        }
        return $letterArray;
    }

}
